package cn.stylefeng.guns.sys.core.util;

import cn.stylefeng.guns.sys.core.constant.factory.ConstantFactory;
import cn.stylefeng.guns.sys.modular.system.model.DictDto;
import cn.stylefeng.guns.sys.modular.system.model.DictTypeDto;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DictUtil {

    public static DictTypeDto get(String code) {
        return ConstantFactory.me().getDictList().get(code);
    }

    public static Boolean has(String code) {
        return ConstantFactory.me().getDictList().containsKey(code);
    }

    public static String all() {
        Map<String, DictTypeDto> dictList = ConstantFactory.me().getDictList();
        Map<String, Map<String, String>> newList = new HashMap<>();
        dictList.forEach((k,v)->{
            Map<String,String> sub = Maps.newHashMap();
            List<DictDto> list = v.getList();
            if(list != null) {
                for (DictDto dictDto : list) {
                    sub.put(dictDto.getCode(), dictDto.getName());
                }
            }
            newList.put(k,sub);
        });
        return JSON.toJSONString(newList);
    }

    public static String get(String code, String value) {
        Map<String, DictTypeDto> dictList = ConstantFactory.me().getDictList();
        if (dictList == null || dictList.isEmpty()) {
            return value;
        }

        DictTypeDto dictTypeDto = dictList.get(code);
        if (dictTypeDto == null) {
            return value;
        }

        List<DictDto> list = dictTypeDto.getList();
        for (DictDto dictDto : list) {
            if (dictDto.getCode().equals(value)) {
                return dictDto.getName();
            }
        }
        return value;
    }
}
